#pragma once

#include <iostream>
#include <memory>
#include <sys/epoll.h>
#include "Socket.hpp"

using namespace SocketModule;

const int gdefaultepfd = -1;

class EpollServer
{
    const static int revs_num = 64;
public:
    EpollServer(uint16_t port)
    :_port(port)
    ,_epfd(gdefaultepfd)
    ,_listen_socket(std::make_unique<TcpSocket>())
    ,_isrunning(false)
    {}

    void Init()
    {
        _listen_socket->BuildTcpSocketMethod(_port);
        // 创建epoll模型
        _epfd = epoll_create(256);
        if (_epfd < 0)
        {
            LOG(LogLevel::ERROR) << "epoll_create error";
            exit(EPOLL_CREATE_ERR);
        }
        LOG(LogLevel::DEBUG) << "epoll_create success, epfd: " << _epfd;
        // 添加listensocket进epoll模型中
        struct epoll_event ev;
        ev.data.fd = _listen_socket->Fd();
        ev.events = EPOLLIN;
        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, _listen_socket->Fd(), &ev);
        if (n < 0)
        {
            LOG(LogLevel::ERROR) << "epoll_ctl error";
            exit(EPOLL_CTL_ERR);
        }
    }

    void Loop()
    {
        _isrunning = true;
        int timeout = -1;
        while (_isrunning)
        {
            int n = epoll_wait(_epfd, _revs, revs_num, timeout);
            switch(n)
            {
            case 0:
                std::cout << "timeout..." << std::endl;
                break;
            case -1:
                perror("epoll_wait");
                break;
            default:
                std::cout << "有事件就绪啦..., timeout" << std::endl;
                Dispatcher(n);
                break;
            }
        }
        _isrunning = false;
    }

    void Accepter()
    {
        InetAddr client;
        int newfd = _listen_socket->Accepter(&client);
        if (newfd < 0)
            return;
        // 将获取的newfd添加到epoll模型中,托管给epoll
        struct epoll_event ev;
        ev.data.fd = newfd;
        ev.events = EPOLLIN;
        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, newfd, &ev);
        if (n < 0)
        {
            LOG(LogLevel::ERROR) << "epoll_ctl error";
            close(newfd);
        }
        LOG(LogLevel::DEBUG) << "epoll_ctl success, sockfd: " << newfd;
    }

    void Recver(int fd)
    {
        char buffer[1024];
        int n = ::recv(fd, buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client# " << buffer << std::endl;
            std::string message = "echo# ";
            message += buffer;
            send(fd, message.c_str(), message.size(), 0);
        }
        else if (n == 0)
        {
            LOG(LogLevel::DEBUG) << "客户端退出, sockfd: " << fd;
            // 要先将fd从epoll模型中移除再close.从epoll模型中移除fd必须保证fd是合法的.
            int m = epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr);
            if (m < 0) 
            {
                LOG(LogLevel::ERROR) << "epoll_ctl error";
                return;
            }
            LOG(LogLevel::DEBUG) << "epoll_ctl success, sockfd: " << fd;
            close(fd);
        }
        else
        {
            LOG(LogLevel::ERROR) << "读取出错, sockfd: " << fd;
            int m = epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr);
            if (m < 0)
            {
                LOG(LogLevel::ERROR) << "epoll_ctl error";
                return;
            }
            LOG(LogLevel::DEBUG) << "epoll_ctl success, sockfd: " << fd;
            close(fd);
        }
    }

    void Dispatcher(int rnum)
    {
        for (int i = 0; i < rnum; i++)
        {
            int fd = _revs[i].data.fd;
            uint32_t revents = _revs[i].events;
            if (fd == _listen_socket->Fd())
            {
                if (revents & EPOLLIN)
                {
                    Accepter();  // 获取连接
                }
            }
            else
            {
                if (revents & EPOLLIN)
                {
                    Recver(fd);  // IO处理
                }
                // else if (revents & EPOLLOUT)
            }
        }
    }

    ~EpollServer()
    {
        _listen_socket->Close();
        if (_epfd >= 0)
            close(_epfd);
    }
private:
    uint16_t _port;
    int _epfd;
    std::unique_ptr<Socket> _listen_socket;
    bool _isrunning;
    struct epoll_event _revs[revs_num];
};